/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.service.email.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.message.SendContextType;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.*;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.message.cache.EmailTemplateCache;
import com.je.message.exception.MessageSendException;
import com.je.message.service.email.EmailOperationService;
import com.je.message.service.email.EmailService;
import com.je.message.service.log.LogServiceFactory;
import com.je.message.vo.EmailMsg;
import com.je.message.vo.LogMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private MetaService metaService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private EmailOperationService emailOperationService;
    @Autowired
    private EmailTemplateCache emailTemplateCache;
    @Autowired
    private SystemVariableRpcService systemVariableRpcService;

    @Override
    public void send(EmailMsg msgVo) {
        String errorMessage = null;
        try {
            emailOperationService.sendEmail(msgVo);
        } catch (Exception e) {
            e.printStackTrace();
            errorMessage = e.getMessage();
            if (Strings.isNullOrEmpty(errorMessage)) {
                errorMessage = e.getLocalizedMessage();
            }
            if (Strings.isNullOrEmpty(errorMessage)) {
                errorMessage = "邮件发送失败，请联系管理员！";
            }
            logger.error("Send email failure {}!", errorMessage, msgVo);
        }
        if (!Strings.isNullOrEmpty(errorMessage)) {
            throw new MessageSendException("邮件发送失败，请联系管理员！");
        }
        LogMsg logMsg = new LogMsg();
        logMsg.setErrorMessage(errorMessage);
        BeanUtils.copyProperties(msgVo, logMsg);
        LogServiceFactory.newLog(LogServiceFactory.LogTypeEnum.EMAIL).saveLog(logMsg);

    }


    @Override
    public void send(String receiveEmail, String subject, String contextType, String context) {
        logger.info("email ----------接受邮箱" + receiveEmail);
        logger.info("email ----------主题" + subject);
        logger.info("email ----------内容" + context);
        EmailMsg msgVo = new EmailMsg(receiveEmail, subject, contextType, context);
        send(msgVo);
    }

    @Override
    public void send(String receiveEmail, String code, Map<String, Object> params) {
        String tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        DynaBean email;
        if (Strings.isNullOrEmpty(tenantId)) {
            email = emailTemplateCache.getCacheValue(code);
        } else {
            email = emailTemplateCache.getCacheValue(tenantId, code);
        }

        if (email == null) {
            email = metaService.selectOne("JE_SYS_EMAILBASE", ConditionsWrapper.builder().eq("EMAILBASE_CODE", code));
            if (Strings.isNullOrEmpty(tenantId)) {
                emailTemplateCache.putCache(code, email);
            } else {
                emailTemplateCache.putCache(tenantId, code, email);
            }
        }
        String title = email.getStr("EMAILBASE_ZT");
        String context = email.getStr("EMAILBASE_NR");
        Map<String, Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        //加入系统设置
        ddMap.putAll(systemSettingRpcService.requireAllSettingValue());
        if (params != null) {
            ddMap.putAll(params);
        }
        title = StringUtil.parseKeyWord(title, ddMap);
        context = StringUtil.parseKeyWord(context, ddMap);
        send(receiveEmail, title, SendContextType.HTML, context);
    }

    @Override
    public void send(String receiveEmail, String subject, String contextType, String context, List<String> fileNames, List<String> addresses) {
        EmailMsg msgVo = new EmailMsg(receiveEmail, subject, contextType, context, fileNames, addresses);
        send(msgVo);
    }

}
